import { Select, Space } from "antd";
import _ from "lodash";
import { useUserContext } from "@/hooks/userHooks";
import { useEffect} from "react";
import { useGoTo } from "@/hooks";
import { ROUTE_KEY } from "@/routes/menus";
import { currentOrg } from "@/utils";
import style from "./index.module.less";
import { useCoursesForSample } from "@/services/course";

interface IProps {
  onSelected: (val: string) => void;
}

/**
 * 课程选择
 */
const CourseSearch = ({ onSelected }: IProps) => {
  // const [courses, setCourses] = useState<ICard[]>();
  const { data, search, loading } = useCoursesForSample();
  const { setStore } = useUserContext();
  const { go } = useGoTo();

  useEffect(() => {
    if (currentOrg()?.value) {
      setStore({
        currentOrg: currentOrg().value,
      });
    } else {
      go(ROUTE_KEY.NO_ORG);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const onSearchHandler = _.debounce((name: string) => {
    search(name)
  }, 500);
  const onChangeHandler = (val: string) => {
    onSelected(val);
  };
  return (
    <Space>
      选择门店:
      <Select
        className={style.select}
        showSearch
        placeholder="请搜索课程"
        onSearch={onSearchHandler}
        onChange={onChangeHandler}
        filterOption={false}
        loading={loading}
      >
        {data?.map((item) => (
          <Select.Option key={item.id} value={item.id}>
            {item.name}
          </Select.Option>
        ))}
      </Select>
    </Space>
  );
};

export default CourseSearch;
